package ylg.com.cn.beuty.main;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;



import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.ServiceUtils;
import org.haitao.common.utils.StatusBarCompat;
import org.haitao.common.utils.ToastUtil;

import ylg.com.cn.beuty.R;
import ylg.com.cn.beuty.Service.DownloadAppService;
import ylg.com.cn.beuty.Service.UpdateManager;
import ylg.com.cn.beuty.entity.Version;
import ylg.com.cn.beuty.http.NetCallBack;
import ylg.com.cn.beuty.http.NetUtils;
import ylg.com.cn.beuty.http.ResultModel;
import ylg.com.cn.beuty.main.fragment.fragment_home.HomeFragement;
import ylg.com.cn.beuty.main.fragment.fragment_home.find_fragment.FindFragment;
import ylg.com.cn.beuty.main.fragment.fragment_home.four_fragment.FourFragment;
import ylg.com.cn.beuty.main.fragment.fragment_home.two_fragment.TwoFragment;

public class MainActivity extends FragmentActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarCompat.compat(this, getResources().getColor(R.color.primary));
        setContentView(R.layout.activity_main);
        findViews();
        init(savedInstanceState);
        chickVersion();
    }

    private long lastTime = 0L;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            //记录当前时间;
            long time = System.currentTimeMillis();
            if((time - lastTime) > 1500){
                Toast.makeText(this,"双击退出",Toast.LENGTH_LONG).show();
                ToastUtil.shortShowToast("双击退出");
            }else{
                finish();
            }
            lastTime = time;
            return  true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private LinearLayout home_lay,talent_lay,me_lay,how_lay;
    private LinearLayout Ly[];

    private void findViews(){
        home_lay = (LinearLayout) findViewById(R.id.tab_home);
        talent_lay = (LinearLayout) findViewById(R.id.tab_talent);
        me_lay = (LinearLayout) findViewById(R.id.tab_me);
        how_lay = (LinearLayout) findViewById(R.id.tab_how);
        Ly = new LinearLayout[]{home_lay, talent_lay, how_lay, me_lay};
    }

    private HomeFragement homeFragement;
    private TwoFragment twoFragment;
    private FindFragment findFragment;
    private FourFragment fourFragment;
    private int currentTabIndex;
    private Fragment fragments[];
    private void init(Bundle savedInstanceState){
        if (savedInstanceState==null){
            homeFragement  = new HomeFragement();
            twoFragment = new TwoFragment();
            findFragment = new FindFragment();
            fourFragment = new FourFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container,homeFragement,HomeFragement.class.getSimpleName())
                    .add(R.id.fragment_container,twoFragment,TwoFragment.class.getSimpleName())
                    .add(R.id.fragment_container,findFragment,FindFragment.class.getSimpleName())
                    .add(R.id.fragment_container,fourFragment,FourFragment.class.getSimpleName())
                    .hide(twoFragment)
                    .hide(findFragment)
                    .hide(fourFragment)
                    .show(homeFragement)
                    .commit();
        }else{
            currentTabIndex = savedInstanceState.getInt("index");
            FragmentManager fmg = getSupportFragmentManager();
            homeFragement = (HomeFragement) fmg.findFragmentByTag(HomeFragement.class.getSimpleName());
            twoFragment = (TwoFragment) fmg.findFragmentByTag(TwoFragment.class.getSimpleName());
            findFragment = (FindFragment) fmg.findFragmentByTag(FindFragment.class.getSimpleName());
            fourFragment = (FourFragment) fmg.findFragmentByTag(FourFragment.class.getSimpleName());
            fragments = new Fragment[]{homeFragement, twoFragment, findFragment, fourFragment};
            fmg.beginTransaction()
                    .hide(homeFragement)
                    .hide(twoFragment)
                    .hide(findFragment)
                    .hide(fourFragment)
                    .show(fragments[currentTabIndex])
                    .commit(); // 显示以前报错的fragment
            // 底部换过来
               replaceFragmet(0, currentTabIndex);
        }
        fragments = new Fragment[]{homeFragement, twoFragment, findFragment, fourFragment};
    }
    /**
     * 切换fragment
     *
     * @param oldIndex 当前的fragment
     * @param newIndex 切换到第几个frament
     */
    public void replaceFragmet(int oldIndex, int newIndex) {
        AppLog.e("--------oldIndex" + oldIndex + "newIndexx" + newIndex+(newIndex != oldIndex));
        if (newIndex != oldIndex) {
            AppLog.e("--------replace to" + newIndex);
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[oldIndex]);
            //trx.show(fragments[newIndex]).commit();
            trx.show(fragments[newIndex]).commitAllowingStateLoss();
            currentTabIndex = newIndex;
            setTabSelect(currentTabIndex);
        }
    }


    private int norId[] = {R.mipmap.ic_tab_home_nor, R.mipmap.ic_tab_budding_nor, R.mipmap.ic_tab_message_nor, R.mipmap.ic_tab_mine_nor,};
    private int preId[] = {R.mipmap.ic_tab_home_hl, R.mipmap.ic_tab_budding_hl, R.mipmap.ic_tab_message_hl, R.mipmap.ic_tab_mine_hl};
    private void setTabSelect(int position) {
        for (int i = 0; i < Ly.length; i++) {
            if (position == i) {
                ((ImageView) Ly[i].getChildAt(0)).setImageResource(preId[i]);
                ((TextView) Ly[i].getChildAt(1)).setTextColor(getResources().getColor(R.color.rose));
            } else {
                ((ImageView) Ly[i].getChildAt(0)).setImageResource(norId[i]);
                ((TextView) Ly[i].getChildAt(1)).setTextColor(getResources().getColor(R.color.text_color));
            }
        }
    }
    public void onTabClicked(View view) {
        int index = 0;
        switch (view.getId()) {
            case R.id.tab_home:
                index = 0;
                break;
            case R.id.tab_talent:
                index = 1;
                break;
            case R.id.tab_how:
                index = 2;
                break;
            case R.id.tab_me:
                index = 3;
                break;
            default:
                break;
        }
        replaceFragmet(currentTabIndex, index);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){

        }
    }
    //检验版本号
    private void chickVersion(){
//        Intent it = new Intent(MainActivity.this, DownloadAppService.class);
//        it.putExtra(DownloadAppService.SERVICRINTENTURL,"");
//        it.putExtra(DownloadAppService.SERVACESHARENAME, 0);
//        startService(it);
        NetUtils.getInstance().chickVersion(new NetCallBack() {
            @Override
            public void onSuccess(String mssage, ResultModel model) {
                final Version version = model.getModel();
                int currentVersion = UpdateManager.getVersionCode(MainActivity.this);
                if (version.getVersionCode()>currentVersion){
                    if (ServiceUtils.isServiceRunning(MainActivity.this, DownloadAppService.serviceName)) {
                        ToastUtil.shortShowToast("升级服务已经启动,无需再次启动");
                    } else {
                        String tishi = getResources().getString(R.string.prompt);

                        AlertDialog.Builder buile = new AlertDialog.Builder(MainActivity.this).setTitle(tishi).setMessage("检查到版本更新").setPositiveButton
                                ("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        Intent it = new Intent(MainActivity.this, DownloadAppService.class);
                                        it.putExtra(DownloadAppService.SERVICRINTENTURL, version.getDownloadUrl());
                                        it.putExtra(DownloadAppService.SERVACESHARENAME, 0);
                                        startService(it);
                                        AppLog.e("启动服务。。。。。。。。。。。。。。");
                                    }
                                }).setNegativeButton("取消", null);
                        Dialog dialog = buile.create();
                        if (!dialog.isShowing()) {
                            dialog.show();
                        }
                    }
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {

            }
        }, Version.class);
    }
}
